package cn.xiaobai.config;

import cn.xiaobai.enums.InitSQL;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库初始化
 *
 * @Author yangdaji
 * @Date 2024/3/24
 * @PackageName cn.xiaobai.config
 * @ClassName DatabaseInit
 */
@Configuration
public class DatabaseInit {

    @Value("${spring.datasource.dbName}")
    private String dbName;

    @Value("${spring.datasource.initUrl}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 初始化库
     */
    @PostConstruct
    public void initDb() {
        String initSql = String.format(InitSQL.INIT_DATABASE.getSql(), dbName);
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.addDataSourceProperty("serverTimezone", "Asia/Shanghai");
        hikariConfig.setMaximumPoolSize(1);
        hikariConfig.setMinimumIdle(1);
        HikariDataSource source = new HikariDataSource(hikariConfig);
        try (Connection connection = source.getConnection();) {
            Statement statement = connection.createStatement();
            statement.executeUpdate(initSql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
